import requests
from lxml import etree
import json
import openpyxl
import os

if not os.path.exists("./data_excel"):
    os.mkdir("./data_excel")


class GetData:
    def __init__(self):
        self.headers = {
            'User-Agent': 'Mozilla / 5.0(Windows NT 10.0;Win64;x64) AppleWebKit / 537.36(KHTML, likeGecko) Chrome / 80.0.3987.87Safari / 537.36'
        }
        self.result = {}
        self.updated_time_in = ''

    def get_data(self):  # 获取数据保存到excel
        url = "https://voice.baidu.com/act/newpneumonia/newpneumonia/"
        response = requests.get(url, headers=self.headers)
        # print (response.text)
        html = etree.HTML(response.text)
        result = html.xpath('//script[@type="application/json"]/text()')  # 返回列表
        # print (result[0])
        self.result = json.loads(result[0])  # 列表第一项为字典; 返回json，使用 json.cn 进行分析; 转化为python对象
        # self.result = result
        # print(self.result)
        # print('slef.result',type(self.result))
        self.updated_time_in = self.result['component'][0]['mapLastUpdatedTime']

    def save_excel(self):
        result_in = self.result['component'][0]['caseList']
        result_out = self.result['component'][0]['caseOutsideList']  # 按 洲 分 gogalList
        # print (result_out)
        wb = openpyxl.Workbook()
        ws = wb.active
        ws.title = '国内疫情数据'
        ws.append(['数据更新时间点：', self.updated_time_in])
        ws.append(['省份', '累计确诊', '死亡', '治愈', '现有确诊', '累计确诊增加数', '死亡增加数', '治愈增加数', '现有确诊增加数'])
        for each in result_in:
            temp_list_in = [each['area'], each['confirmed'], each['died'], each['crued'], each['curConfirm'],
                            each['confirmedRelative'],
                            each['diedRelative'], each['curedRelative'], each['curConfirmRelative']]
            ws.append(temp_list_in)

        ws_out = wb.create_sheet('国外疫情数据')
        ws_out.append(['数据更新时间点：', self.updated_time_in])
        ws_out.append(['国家', '累计确诊', '死亡', '治愈', '现有确诊', '累计确诊增加数'])
        for each in result_out:
            temp_list_out = [each['area'], each['confirmed'], each['died'], each['crued'], each['curConfirm'],
                             each['confirmedRelative']]
            for i in range(len(temp_list_out)):
                if temp_list_out[i] == '':
                    temp_list_out[i] = '0'
            ws_out.append(temp_list_out)

        day_time = self.updated_time_in[0:11]
        wb.save("./data_excel/datas-{}.xlsx".format(day_time))
        print('Excel已保存')

    def updated_time(self):
        updated_time_in = self.updated_time_in
        # updated_time_out = self.result['component'][0]['foreignLastUpdatedTime']
        # print(updated_time_in)
        # print (type(updated_time_in))
        return updated_time_in

    def used_data(self):
        data_in = self.result['component'][0]['caseList']
        data_out = self.result['component'][0]['caseOutsideList']
        sum_china = self.result['component'][0]['summaryDataIn']
        # print('data_in', type(data_in))
        # print(data_in)
        # print(area , confirmeds)       
        return data_in, data_out, sum_china


if __name__ == '__main__':
    data = GetData()
    data.get_data()
    data.save_excel()
    data.updated_time()
    data.used_data()

'''
area -->省份/直辖市/特别行政区等
city -->城市
confirmed --> 累计确诊人数
died --> 死亡人数

crued --> 治愈人数
confirmedRelative --> 累计确诊的增加数
curedRelative --> 治愈的增加数
curConfirm --> 现有确诊人数
curConfirmRelative --> 现有确诊的增加数
diedRelative --> 死亡的增加数

'''
